import pytest
import os
import json
from utils.api_client import APIClient
from utils.logger import logger
from config.config import config

@pytest.fixture(scope="session")
def api_client():
    """
    创建API客户端实例
    """
    client = APIClient()
    return client

@pytest.fixture(scope="session")
def admin_token(api_client):
    """
    获取管理员token
    """
    # 先获取验证码
    api_client.get_verification_code()
    
    # 登录获取token
    admin_user = config.get_admin_user()
    response = api_client.login(
        username=admin_user['username'],
        password=admin_user['password']
    )
    
    assert response.status_code == 200, "管理员登录失败"
    return api_client.token

@pytest.fixture(scope="session")
def test_user_token(api_client):
    """
    获取测试用户token
    """
    # 先获取验证码
    api_client.get_verification_code()
    
    # 登录获取token
    test_user = config.get_test_user()
    response = api_client.login(
        username=test_user['username'],
        password=test_user['password']
    )
    
    # 如果用户不存在，则注册
    if response.status_code != 200:
        # 获取注册验证码
        api_client.get_verification_code('register')
        
        # 注册用户
        register_response = api_client.post(
            '/user/users/',
            json_data={
                'username': test_user['username'],
                'password': test_user['password'],
                'verify': '1234',  # 假设验证码
                'uuid': api_client.uuid_val
            }
        )
        
        assert register_response.status_code == 201, "测试用户注册失败"
        
        # 重新登录
        api_client.get_verification_code()
        response = api_client.login(
            username=test_user['username'],
            password=test_user['password']
        )
    
    assert response.status_code == 200, "测试用户登录失败"
    return api_client.token

@pytest.fixture(scope="function")
def clean_test_data():
    """
    测试前后清理测试数据
    """
    # 测试前准备
    yield
    # 测试后清理
    # 这里可以添加清理测试数据的代码
    pass